import 'package:common_utils/common_utils.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:nft_shop/box/page/details/box_details_page.dart';
import 'package:nft_shop/login/page/login_page.dart';
import 'package:nft_shop/market/model/models.dart';
import 'package:nft_shop/market/page/details/works_details_page.dart';
import 'package:nft_shop/net/service_repository.dart';
import 'package:nft_shop/res/constant.dart';
import 'package:nft_shop/res/global.dart';
import 'package:nft_shop/sift/conteroller/sift_conteroller.dart';
import 'package:nft_shop/sift/view/sift_list_item_widget.dart';
import 'package:nft_shop/widgets/load_image.dart';
import 'package:nft_shop/widgets/status_view.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class SiftListPage extends StatefulWidget {
  int? index;

  SiftListPage({Key? key, this.index}) : super(key: key);

  @override
  _SiftListPageState createState() => _SiftListPageState();
}

class _SiftListPageState extends State<SiftListPage>
    with AutomaticKeepAliveClientMixin {
  ///刷新组件
  RefreshController refreshController =
      RefreshController(initialRefresh: false);

  /// 分页第一页页码
  static const int pageNumFirst = 1;

  /// 当前第几页
  int currentPageNum = pageNumFirst;

  /// 分页条目数量
  int pageSize = 15;

  /// 页面数据
  List list = [];

  ///状态
  int _status = LoadStatusType.loading;

  int get status => _status;

  set status(int value) {
    _status = value;
    setState(() {});
  }

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    refresh();
    SiftConteroller.to.refreshBlock = () {
      print("刷新数据----");
      refresh();
    };
  }

  //获取数据
  Future<List> loadData({int? pageNum}) async {
    return await ServiceRepository.goodsSpecialList(
        page: 1,
        pageSize: pageSize,
        isHot: widget.index == 0 ? 1 : 0,
        isNow: 0,
        will: widget.index == 1 ? 1 : 2,
        orderType: 3,
        // isHot: widget.index == 0 ? 1 : 0,
        // isNow: widget.index == 1 ? 1 : 0,
        // will: widget.index == 2 ? 1 : 2,
        type: 0);
  }

  /// 下拉刷新
  ///
  /// [init] 是否是第一次加载
  /// true:  Error时,需要跳转页面
  /// false: Error时,不需要跳转页面,直接给出提示
  Future<List?> refresh({bool init = false}) async {
    try {
      currentPageNum = pageNumFirst;
      var data = await loadData(pageNum: pageNumFirst);
      if (data.isEmpty) {
        refreshController.refreshCompleted(resetFooterState: true);
        list.clear();
        status = LoadStatusType.empty;
      } else {
        list.clear();
        list.addAll(data);
        refreshController.refreshCompleted();
        // 小于分页的数量,禁止上拉加载更多
        if (data.length < pageSize) {
          refreshController.loadNoData();
        } else {
          //防止上次上拉加载更多失败,需要重置状态
          refreshController.loadComplete();
        }
        status = LoadStatusType.success;
        setState(() {});
      }
      return data;
    } catch (e, s) {
      /// 页面已经加载了数据,如果刷新报错,不应该直接跳转错误页面
      /// 而是显示之前的页面数据.给出错误提示
      if (init) list.clear();
      refreshController.refreshFailed();
      status = LoadStatusType.empty;
      // setError(e, s);
      return null;
    }
  }

  /// 上拉加载更多
  Future<List?> loadMore() async {
    try {
      var data = await loadData(pageNum: ++currentPageNum);
      if (data.isEmpty) {
        currentPageNum--;
        refreshController.loadNoData();
      } else {
        list.addAll(data);
        if (data.length < pageSize) {
          refreshController.loadNoData();
        } else {
          refreshController.loadComplete();
        }
        setState(() {});
      }
      return data;
    } catch (e, s) {
      currentPageNum--;
      refreshController.loadFailed();
      return null;
    }
  }

  @override
  Widget build(BuildContext context) {
    if (status != LoadStatusType.success) {
      return StatusViews(status);
    }

    // return ListView.builder(
    //   shrinkWrap: true,
    //   itemCount:list.length,
    //   physics: const NeverScrollableScrollPhysics(),
    //   itemBuilder: (_, index) {
    //     return SiftListItem(model:list[index]);
    //   },);

    return SmartRefresher(
        enablePullDown: true,
        controller: refreshController,
        header: WaterDropHeader(),
        onRefresh: refresh,
        child: ListView.builder(
          shrinkWrap: true,
          itemCount: list.length,
          physics: const NeverScrollableScrollPhysics(),
          itemBuilder: (_, index) {
            return SiftListItemWidget(
                model: list[index],
                onPressed: () {
                  refresh();
                });
          },
        ));
  }
}
